import { defineComponent } from 'vue';
import { dayjs, ElMessageBox } from 'element-plus';
import type { Action } from 'element-plus';
import { nanoid } from 'nanoid';
import axios from 'axios';
import ImageUploader from 'quill-image-uploader';
import { addGoods, getGoodList, delGoods, updateGoods } from '@/api/goods';

export default defineComponent({
  data() {
    return {
      showAddDialog: false,
      fileList: [],
      goods: {
        name: '',
        number: 1,
        inMoney: 0,
        goodno: '',
        unit: '',
        actionUser: '',
        deadLine: '',
        suply: '',
        cover: '',
        desc: '',
      },
      editGoods: {
        id: 0,
        name: '',
        number: 1,
        inMoney: '',
        goodno: '',
        unit: '',
        actionUser: '',
        deadLine: '',
        suply: '',
      },
      list: [],
      limit: 30,
      page: 1,
      total: 0,
      showEdit: false,
      rules: {
        name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        inMoney: [
          { required: true, message: '填写商品价格', trigger: 'blur' },
          {
            trigger: 'blur',
            validator(rule: any, value: any, callback: any) {
              if (value >= 3 && value <= 100) {
                callback();
              } else {
                callback(new Error('一定要在这个范围'));
              }
            },
          },
        ],
      },
      modules: {
        name: 'imageUploader',
        module: ImageUploader,
        options: {
          upload(file: any) {
            console.log('file', file);
            return new Promise((resolve) => {
              const formdata = new FormData();
              formdata.append('file', file);
              formdata.append('type', 'qf2302');
              axios
                .post('http://www.wzsqyg.com/attachment/upload', formdata)
                .then((reulst: any) => {
                  console.log('reulst', reulst);
                  resolve(reulst.data.msg);
                });
            });
          },
        },
      },
    };
  },
  mounted() {
    this.getList(); // 获取列表内容
  },
  methods: {
    handleUpload(options: any) {
      // 实际工作当中我们更多的是自己去执行上传的具体操作 因为上传前我们还有可以需要进行压缩操作等
      console.log('options', options);
      // options.file就是我们要上传的文件对象
      const formdata = new FormData();
      formdata.append('file', options.file); // 实践当中对于这个file对象一般还需要进行压缩处理等
      formdata.append('type', 'qf2302');
      return axios.post('http://www.wzsqyg.com/attachment/upload', formdata);
    },
    handleBeforeUpload(rawFile: any): boolean {
      console.log('rawFile', rawFile);
      // 使用上传之前的钩子我们可以对于上传的文件进行检测或者大小的判断
      if (!rawFile.type.includes('image')) {
        this.$message.warning('只能上传图片文件');
        return false;
      }
      const min = 0.001 * 1024 * 1024;
      if (rawFile.size < min) {
        this.$message.warning('上传的图片不能小于0.2m');
        return false;
      }
      return true;
    },
    handleUploadOk(response: any) {
      console.log('response', response);
      this.goods.cover = response.msg;
    },
    openEdit(row: any) {
      this.editGoods = row;
      this.showEdit = true;
    },
    handeSizeChange(val: number) {
      console.log('val', val);
      this.limit = val;
      this.getList();
    },
    handlePageChange(val: number) {
      this.page = val;
      this.getList();
    },
    async handleAdd() {
      console.log('goods', this.goods);
      console.log('$refs.addfrom', this.$refs.addfrom);
      try {
        const validateRes = await (this.$refs.addfrom as any).validate();
        console.log('validateRes', validateRes);
        // 确保表单完全的通过校验规则
        const res = await addGoods(this.goods);
        console.log('res', res);
        const { status } = res;
        if (status === 201) {
          this.$message.success('添加成功');
          this.showAddDialog = false;
          this.getList();
        } else {
          this.$message.warning('添加失败');
        }
      } catch (e) {
        this.$message.warning('请按要求检查表单内容');
      }
    },
    async handleEidt() {
      console.log('goods', this.editGoods);
      const { id, ...postdata } = this.editGoods;
      const res = await updateGoods(id, postdata);
      console.log('res', res);
      const { status } = res;
      if (status === 200) {
        this.$message.success('修改成功');
        this.showEdit = false;
        this.getList();
      } else {
        this.$message.warning('修改失败');
      }
    },
    handleOpen() {
      const datestr = dayjs().format('YYYYMMDD');
      const uid = nanoid(5);
      this.goods.goodno = `qf${datestr}${uid}`;
    },
    async getList() {
      const $skip = (this.page - 1) * this.limit;
      const res = await getGoodList({
        $skip,
        $limit: this.limit,
      });
      console.log('获取列表的结果', res);
      this.list = res.data.data;
      this.total = res.data.total;
    },
    showUnit(val: number | string) {
      val = Number(val);
      if (val === 1) return '件';
      if (val === 2) return '箱';
      return '瓶';
    },
    formatTime(time: string) {
      return dayjs(time).format('YYYY-MM-DD');
    },
    handleDel(id: number) {
      // 删除的操作一般需要二次确认 避免用户误操作
      ElMessageBox.alert('删除？确定?不后悔？', '想清楚了没', {
        confirmButtonText: 'OK',
        callback: async (action: Action) => {
          if (action === 'cancel') return false;
          const res = await delGoods(id);
          console.log('真正的去执行删除', res);
          if (res.status === 200) {
            this.$message.success('删除成功');
            this.getList();
          } else {
            this.$message.warning('删除失败');
          }
          return true;
        },
      });
    },
  },
});
